/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.apps.group.admin.shiro.ShiroDbRealm;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.util.ConfigUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController
{
	@Autowired
	ConfigUtil configUtil;
	@Autowired
	UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		return "account/login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, @RequestParam(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM) String password,Model model) {
		//return "redirect:/logout";
		ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if(null != user && user.getMobile().equals(userName) )
			return "redirect:/dashboard";

		SecurityUtils.getSubject().logout();
		return "redirect:/logout";
	}

	protected AuthenticationInfo doGetAuthenticationInfo(String username,String password) throws AuthenticationException
	{
		//System.out.println("username------------------->" + token.getUsername());
		//System.out.println("password------------------->" + String.valueOf(token.getPassword()));
		//User user = userService.findByMobile(token.getUsername());
		User user = userService.login(username,password);
		if (user != null) {
			//System.out.println("------------> is not null ");
			return new SimpleAuthenticationInfo(new ShiroDbRealm.ShiroUser(user.getId(), user.getMobile(), user.getRealName()),
					user.getPassword(),user.getRealName());
		} else {
			//System.out.println("------------> is null ");
			return null;
		}
	}
}
